<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/10/13
 * Time: 6:08 PM
 */

namespace app\zyhsapi\model;

use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsAppVersion extends BaseCacheZyhs
{
    protected $table = 'good_wechatadmin.zyhs_app_version';
    protected $cacheModel = 'config.version';

    /**
     * 最新版本信息
     * @param array $map
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getVersionData($map = [])
    {
        // 获取最新的版本信息
        return CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $map['type'])->getDataAndSet(function () use ($map)
        {
            return $this->getVersionDataByDb($map['type']);
        });
    }

    /**
     * 指定版本信息
     * @param $type
     * @param $version
     * @param array $field
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getVersionInfo($type, $version, $field = [])
    {
        $key = $type . ':V' . $version;

        $versionName = 'V' . $version;

        $versionInfo = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $key)->getDataAndSet(function () use ($type, $versionName)
        {
            return $this->getVersionDataByDb($type, $versionName, 0);
        }, $field);
        if ($versionInfo)
        {
            $versionInfo['extend'] = json_decode($versionInfo['extend'], true);
        }
        return $versionInfo;
    }

    /**
     * 获取版本信息
     * @param string $type 客户端类型  ios  android
     * @param string $version 版本号：1.9.4
     * @param int $status 特殊情况下，需要获取未开启的版本
     * @return array
     */
    protected function getVersionDataByDb($type, $version = null, int $status = 1): array
    {
        try
        {
            $where = ['type' => $type];
            if ($version)
            {
                $where['version_name'] = $version;
            }
            if ($status === 1)
            {
                $where['status'] = $status;
            }
            $data = $this
                ->field('*')
                ->where($where)
                ->order('id DESC')->findOrFail()->toArray();
        }
        catch (\Exception $e)
        {
            return [];
        }

        return $data;
    }

    /**
     * 苹果沙箱状态
     * @return bool
     * @throws \Exception
     */
    public static function iosSandboxModel()
    {
        $header = request()->header();
        $appVersion = (new ZyhsAppVersion())->getVersionInfo($header['app-type'], $header['version']);
        return (bool)((int)$appVersion['extend']['ios']['apple_pay_sandbox_model']);//获取苹果沙箱状态
    }
}
